package pl.vojna.ant_alg.algorithms;

import java.util.Arrays;

import pl.vojna.ant_alg.Algorithm;
import pl.vojna.ant_alg.Problem;
import pl.vojna.ant_alg.Utils;

/**
 * Implementacja losowego przeszukiwania przestrzeni rozwiązań.
 * 
 * @author kolar
 * 
 */
public class RandomSearch implements Algorithm {
	@Override
	public int[] solve(Problem problem, int size, Boolean isDebug,
			int numOfIterations) {
		int problemSize = problem.getSize();
		int[] solution = new int[problemSize];
		initSolution(problemSize, solution);
		int[] bestSolution = Arrays.copyOf(solution, solution.length);
		int bestCost = Utils.solutionCost(problem, bestSolution);

		for (int iteration = 1; iteration < numOfIterations; iteration++) {
			Utils.shuffleArray(solution);
			int cost = Utils.solutionCost(problem, solution);

			if (cost < bestCost) {
				if (isDebug) {
					Utils.showSolution(solution);
					System.out.println("cost:" + cost);
				}
				bestSolution = Arrays.copyOf(solution, solution.length);
				bestCost = Utils.solutionCost(problem, bestSolution);
			}
		}
		return bestSolution;
	}

	private void initSolution(int problemSize, int[] solution) {
		for (int i = 0; i < problemSize; i++) {
			solution[i] = i;
		}
	}

}
